/******************** 
	作用:商品详情页
	作者:蔡俊雄
	版本:V1.0
	时间:2015-09-01
	修改:2015-09-02
********************/

$(function() {
	//--------------------滑动切换图片
	var mc = new Hammer(document.getElementById('image-list'));
	mc.on("panleft", function(e) {
		$('#image-list').carousel('next');
	});
	mc.on("panright", function(e) {
		$('#image-list').carousel('prev');
	});
	//-----------------限制只能输入数字-----------------
	var commonCheckStr = "input[type=text]"; //检查的字符串
	var eventName = 'keyup blur paste';

	$("#count").delegate(null, eventName, function(e) {
		if (e.type == "focusout" || e.type == "paste") {
			checkIsNumber($(e.target), true); //检查输入值是否为数字
		} else {
			checkIsNumber($(e.target)); //检查输入值是否为数字
		}
	});


	/**
	 * 检查输入值是否为数字
	 * @param {String} element 目标元素
	 * @param {Boolean} checkValid 检查数字是否有效
	 */
	function checkIsNumber(element, checkValid) {
		var value = element.val().replace(/[^0123456789]/g, '');
		if (value == "") {
			value = 1;
		}
		if (checkValid) {
			var re = /^[1-9]\d*|^[1-9]\d*\d*|0\.\d*[1-9]\d*$/; //非负整数+小数点  							
			if (!re.test(value) && value != "") {
				$(element).val(1);
			} else {
				element.val(value);
			}
		} else {
			element.val(value);
		}
	};
	
	
	//-----------------计算总价-----------------
	//保留两位小数
	function toFixed2(num) {
	
	}
	//计算总价
	function countTotal() {
		try {
			var currentCount = $("#count").val();
			currentCount = parseInt(currentCount);
			if (isNaN(currentCount)) {
				currentCount = 0;
			}
			var currentPrice = $("#price").html();
			currentPrice = parseFloat(currentPrice);
			if (isNaN(currentPrice)) {
				currentPrice = 0;
			}
			currentPrice *= currentCount;
			//取两位小数
			currentPrice=Math.round(currentPrice*100)/100;
			$("#totalMoney").html(currentPrice);
		} catch (e) {}
	};
	$("#plus").click(function() {
		var result = 1;
		try {
			var c = $("#count").val();
			c = parseInt(c);
			if (isNaN(c)) {
				c = 0;
			}
			result = c;
			result++;
			var max = parseInt($("#count").attr('max'));
			if(max>0 && max<result){
				General.alert('该商品为限购商品，最多只能购买'+max+'件');
				return false;
			}
			$("#count").val(result);
			countTotal(); //计算总价
		} catch (e) {}
	});
	$("#minus").click(function() {
		var result = 1;
		try {
			var c = $("#count").val();
			c = parseInt(c);
			if (isNaN(c)) {
				c = 0;
			}
			result = c;
			result--;
			if (result < 1)
				result = 1;
			$("#count").val(result);
			countTotal(); //计算总价
		} catch (e) {}
	});

	//-----------------切换收藏状态-----------------
	//切换收藏状态
	function toggleFavorit() {
		var f = $(".favorite");
		var icon = f.find("i");
		var state = f.find("span");
		if (icon.hasClass("fa-star-o")) {
			icon.removeClass("fa-star-o").addClass("fa-star");
			state.html("已收藏");
		} else {
			icon.removeClass("fa-star").addClass("fa-star-o");
			state.html("收藏");
		}
	}
	window.toggleFavorit = toggleFavorit;

	//-----------------切换不同属性时显示相应的价格-----------------
	//格式说明:
	//property1:属性1被选中第几个
	//property2:属性2被选中第几个
	//stock:属性2被选中第几个
	//price:价格
	var priceData = [];
	/*var priceData = [{
		"property1": 1,
		"property2": 1,
		"stock": 1,
		"originalPrice": "150.00",
		"price": "120.10"
	}, {
		"property1": 1,
		"property2": 2,
		"stock": 5,
		"originalPrice": "160.00",
		"price": "130.50"
	}, {
		"property1": 2,
		"property2": 1,
		"stock": 0,
		"originalPrice": "130.00",
		"price": "100.60"
	}, {
		"property1": 2,
		"property2": 2,
		"stock": 8,
		"originalPrice": "50.00",
		"price": "30.20"
	}, {
		"property1": 3,
		"property2": 1,
		"stock": 12,
		"originalPrice": "99.00",
		"price": "88.00"
	}, {
		"property1": 3,
		"property2": 2,
		"stock": 0,
		"originalPrice": "180.00",
		"price": "92.00"
	}];*/
	//	console.log(JSON.stringify(priceData));
	//切换不同属性时显示相应的价格
	function initProperty() {
		try {
			priceData = eval($("#priceData").val());
		} catch (e) {
			priceData = [];
		}
		$("#sku .row-content").each(function() {
			$(this).find(".property").each(function(index) {
				$(this).attr("data-index",(index+1)+"");
			});
		});
		
		$("#sku .property").on("click", function(e) {
			General.stopEvent(e);
			if($(this).hasClass('nofocus'))return false;
			$(this).siblings(".property").removeClass("selected");
			$(this).toggleClass("selected");
			showPrice(); //显示相应的价格
			//			General.alert("加载中...");
		});
		//默认选择第一个
		//$("#sku .property").eq(0).addClass("selected");
		showPrice(); //显示相应的价格
	};
	//显示相应的价格
	function showPrice() {
		var propertyIndexs = [];
		var selectedCount = 0; //选择
		$("#sku .row-content").each(function(i) {
			var index =$(this).find(".selected").index();
			if (index != -1) {
				selectedCount++;
				//被选中,判断另外一个属性的选项是否需要隐藏起来
				if (priceData.length > 0) {
					$.each(priceData, function(key, data) {
						//i+1:被选中的是第几个属性
						//index+1:属性被选中的是第几个选项
						if (data["property" + (i + 1)] == (index + 1)) {
							var propertyIndex = 1 - i;
							var optionIndex = data["property" + (2 - i)] - 1;
							if (data["stock"] <= 0) {
								$("#sku .row-content:eq(" + propertyIndex + ") .property:eq(" + optionIndex + ")").addClass("nofocus");
							} else {
								//库存不为0,将另外一个属性的相应选项显示起来
								$("#sku .row-content:eq(" + propertyIndex + ") .property:eq(" + optionIndex + ")").removeClass("nofocus");
							}
						}
					});
				}
			} else {
				//没被选中,将另一个属性的所有选项显示出来
				$("#sku .row-content:eq(" + (1 - i) + ") .property").removeClass("nofocus");
			}
			propertyIndexs.push(++index);
		});
		if (selectedCount == 2) {
			var findedData = null; //找到的商品数据
			if (priceData.length > 0) {
				$.each(priceData, function(index2, obj) {
					if (obj["property1"] == propertyIndexs[0] && obj["property2"] == propertyIndexs[1]) {
						findedData = obj;
						return false;
					}
				});
			}
			if (findedData !== null) {
				$("#price").html(findedData["price"]);
				$("#originalPrice").html(findedData["originalPrice"]);
				$("#stock").html(findedData["stock"]);
				countTotal(); //计算总价
			}
		}
	};
	initProperty(); //切换不同属性时显示相应的价格

	//-----------------购物车-----------------
	//切换不同属性时显示相应的价格
	function initCart() {
		var $addProductToCart=$("#addProductToCart");
		var publicUrl=$addProductToCart.attr("data-href");
		var pulbicIsEmptyParam=parseInt($addProductToCart.attr("data-isEmptyparam"));
		var pubOpTyle=1;//1加入购物车  2立即购买
		$("#addProductToCart").on("click", function(e) {
			General.stopEvent(e);
			var url = $(this).attr("data-href");
			if(pulbicIsEmptyParam==1){
				addToCart(url);
				return;
			}
			
			
			publicUrl=url;
			pubOpTyle=1;
			$windowSku.modal();
		});
		$("#buy").on("click", function(e) {
			General.stopEvent(e);
			var url = $(this).attr("data-href");
			if(pulbicIsEmptyParam==1){
				buyNow(url);
				return;
			}
			publicUrl=url;
			pubOpTyle=2;
			$windowSku.modal();
		});
		
		
		//弹出sku选择框
		var $windowSku=$('#windowSku');
		$("#btnPopSku").click(function(){
	        $windowSku.modal();
	      });
		$("#windowSkuBtnOk").click(function(){
			var url=publicUrl;
			if(pubOpTyle==1){  //加入购物车
				//判断属性是否被选中
				var properties = $("#sku .property");
				if (properties.length > 0) {
					//多属性
					var count = properties.filter(".selected").length;
					if (count < 1) {
						General.alert("请先选择产品属性！");
					} else {
						//开始添加到购物车
						addToCart(url);
					}
				} else {
					//开始添加到购物车
					addToCart(url,$addProductToCart);
				}
			}else if(pubOpTyle==2){  //立即购买
				//判断属性是否被选中
				var properties = $("#sku .property");
				//			console.log(properties)
				if (properties.length > 0) {
					//多属性
					var count = properties.filter(".selected").length;
					if (count < 1) {
						General.alert("请先选择产品属性！");
					} else {
						//开始添加到购物车
						buyNow(url);
					}
				} else {
					//开始添加到购物车
					buyNow(url);
				}
			}
			$windowSku.modal('hide');
			
			
		});
	};

	//判断是否有产品的SKU
	function hasSku() {
			var result = $("#sku .property").length > 0;
			return result;
		}
		//获取产品的SKU

	function getProductSku() {
		var data = [];
		if (hasSku()) {
			$("#sku .row-content").each(function(i) {
				var sku = $(this).find(".selected").attr("data-value");
				data.push(sku);
			});
		}
		return data.join(",");
	};
	//开始添加到购物车
	function addToCart(url) {
		var id = $("#productId").val(); // 购物车商品ID
		var sku = getProductSku(); // sku信息
		var num = $("#count").val();
		var data = {
			goods_id: id,
			quantity: num,
			spec: sku
		};
		Common.ajaxPostWantResult(url, data, "", null, null, true, addAnimation,num, true);
	};

	// 立即购买
	function buyNow(url){
		var id = $("#productId").val(); // 购物车商品ID
		var sku = getProductSku(); // sku信息
		var num = $("#count").val();
		var data = {
			goods_id: id,
			quantity: num,
			spec: sku
		};
		Common.ajaxPostWantResult(url, data, "", null, null, true, 
			function(data){
				window.location.href = '/shop/cart/';
			}, 
		num, true);
	}
	//飞入购物车的动画
	var startFly_pageX=0,startFly_pageY=0;
	function startFly(){
		var offset = $("#movieBuyEnd").offset();
		var addcar =$('#image-list .active');
		var img = addcar.find('img').attr('src');
		var flyer = $('<img src="'+img+'" width="80%">');
		flyer.fly({
			start: {
				left: 5,
				top: 80
			},
			end: {
				left: offset.left+10,
				top: offset.top+10,
				width: 0,
				height: 0
			},
			onEnd: function(){
				this.destory();
			}
		});
	}
	//添加动画
	function addAnimation(data) {
		//
		var num=data["successParam"];
		//购物车数量
		var count = parseInt($("#cartProductCount").html());
		num = parseInt(num);
		if (isNaN(count)) {
			count = 0;
		}
		if (isNaN(num)) {
			num = 0;
		}
		if(num!=0){
			num += count;
			$("#cartProductCount").html(num);
			//进入到购物车的动画
			startFly($("#addProductToCart"));
		}else{
			alert('获得产品信息错误');
		}
		
	}
	initCart();

	
	//-----------------动态调整窗口大小-----------------
	adjustIframe();

	function adjustIframe() {
		var maxHeight = 0.96;
		var height = $(window).height();
		height *= maxHeight;
		//获取图片大小
		var imgHeight = $("#shareImage").height();
		//      console.log(imgHeight+":"+height);
		if (height < imgHeight) {
			imgHeight = height;
			$("#shareImage").css("height", imgHeight + "px");
		} else {
		}
	}
	$(window).resize(adjustIframe);
});